﻿var post_vm = avalon.define({
    $id: 'post_eidt',
    post: null,
    categories: null,

    save_post: function () {
        window.editor.sync();
        post_vm.post.Detail = $('#detail').val();

        var data = [];
        for (var key in post_vm.post) {
            if (key != null) {
                data.push({
                    name: key,
                    value: post_vm.post[key]
                });
            }
        }

        var categories = $('#category_select').val();

        _.each(categories, function (categoryID) {
            data.push({
                name: 'categoryIDs',
                value: categoryID
            });
        });

        $.post('/post/save', data).success(post_vm.on_save_post_success).error(post_vm.on_save_post_error);
    },
    on_save_post_success: function (result) {
        post_vm.post.ID = result.ID;
        $('title').text('编辑')
        success_msg("保存成功");
    },
    on_save_post_error: function () {
        error_msg("保存失败");
    },
    set_category: function () {

        var post_categories_id = [];

        _.each(this.post.Categories, function (category) {
            post_categories_id.push(category.ID);
        });

        _.each(this.categories, function (category) {
            if (post_categories_id.indexOf(category.ID) > -1) {
                category.is_checked = true;
            }
        });
    },
    set_status: function () {
        $('input[name="status"][value="' + this.post.Status + '"]').prop('checked', true);
    },
    change_status: function (status) {
        post_vm.post.Status = status;
    },
    upload_file: function (file) {
        var option = {
            url: '/image',
            fieldName: 'fileData'
        }

        new FileUpload(option, file).upload(this.upload_picture_success);
    },
    upload_picture_success: function (data) {
        post_vm.post.FirstPicture = data.Path;
    },
    edit_first_picture: function () {
        if (!post_vm.post.FirstPicture) {
            layer.msg('请先上传封面图片');
            return;
        }

        var index = layer.open({
            type: 2,
            content: '/image/edit?path=' + post_vm.post.FirstPicture,
            area: ['100%', '100%'],
            maxmin: true
        });
        layer.full(index);
    }
});

post_vm.post = JSON.parse($('#post_data').val());
post_vm.categories = JSON.parse($('#category_data').val());

post_vm.set_category();
post_vm.set_status();

function uploadFile(file) {
    post_vm.upload_file(file.files[0]);
}

function editPictureCallBack(picturePath) {
    layer.closeAll();
    post_vm.post.FirstPicture = picturePath;
}